import React, { useEffect, useState } from 'react';
import {
  View,
  Text,
  FlatList,
  Image,
  StyleSheet,
  ActivityIndicator,
} from 'react-native';
import { getArticleList } from '@api/base';
import type { Article } from './type';

// 工具函数：去除 HTML 标签
function stripHtml(html: string) {
  return html
    .replace(/<[^>]+>/g, '')
    .replace(/&nbsp;/g, ' ')
    .trim();
}

const ArticleList: React.FC = () => {
  const [articles, setArticles] = useState<Article[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    getArticleList()
      .then(res => {
        setArticles(res?.data?.list || []);
      })
      .catch(e => {
        console.log('error', e);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  const renderItem = ({ item }: { item: Article }) => (
    <View style={styles.card}>
      <View style={styles.header}>
        <Image
          source={{
            uri: item?.authorAvatar
              ? item?.authorAvatar
              : 'https://cdn.z.wiki/autoupload/20250511/XTyv/770X778/df-avatar.png',
          }}
          style={styles.avatar}
        />
        <View>
          <Text style={styles.author}>{item.authorName}</Text>
          <Text style={styles.date}>{formatDate(item.createdAt)}</Text>
        </View>
        <View style={styles.categoryBox}>
          <Text style={styles.category}>{item.category}</Text>
        </View>
      </View>
      <Text style={styles.title}>{item.title}</Text>
      <Text style={styles.summary} numberOfLines={3}>
        {stripHtml(item?.content || '').slice(0, 60)}
      </Text>
    </View>
  );

  if (loading) {
    return <ActivityIndicator style={{ marginTop: 40 }} />;
  }

  return (
    <FlatList
      data={articles}
      keyExtractor={item => String(item.id)}
      renderItem={renderItem}
      contentContainerStyle={{ padding: 16 }}
    />
  );
};

function formatDate(dateStr: string) {
  const d = new Date(dateStr);
  return `${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()}`;
}

const styles = StyleSheet.create({
  card: {
    backgroundColor: '#fff',
    borderRadius: 12,
    padding: 16,
    marginBottom: 16,
    shadowColor: '#000',
    shadowOpacity: 0.08,
    shadowRadius: 8,
    shadowOffset: { width: 0, height: 2 },
    elevation: 2,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    marginBottom: 8,
  },
  avatar: {
    width: 36,
    height: 36,
    borderRadius: 18,
    marginRight: 10,
    backgroundColor: '#eee',
  },
  author: {
    fontWeight: 'bold',
    fontSize: 15,
  },
  date: {
    color: '#888',
    fontSize: 12,
  },
  categoryBox: {
    marginLeft: 'auto',
    backgroundColor: '#e0f0ff',
    borderRadius: 8,
    paddingHorizontal: 8,
    paddingVertical: 2,
  },
  category: {
    color: '#2196f3',
    fontSize: 12,
  },
  title: {
    fontSize: 18,
    fontWeight: 'bold',
    marginVertical: 6,
    color: '#222',
  },
  summary: {
    color: '#555',
    fontSize: 15,
    marginTop: 2,
  },
});

export default ArticleList;
